import { getPage, getImage } from '../../utils/config';
import { http, countMode, storage, $query, $toast } from '../../utils/utils';
import api from '../../utils/api';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        getPage: getPage,
        getImage: getImage,
        initial: 0,
        loading: 0,
        logged: 0,
        userId: '',
        userRank: '',
        operat: true,
        cartInfo: {},
        couponInfo: [],
        allCheckbox: false,
        showCoupon: false,
        goodsCount: 0,
        sumAmount: 0,
        sumCount: 0,
        pageIndex: 0,
        cartIdList: [],
        sumRecommend: [],
        loadmore: true,
        loaddone: false,
    },

    toggle(type) {
        this.setData({
            [type]: !this.data[type]
        });
    },

    doNothing() {},

    /**
     * 跳转首页
     */
    goShopping() {
        wxApi.switchTab(getPage.home);
    },

    /**
     * 底部导航点击
     */
    onTabItemTap() {
        const { logged, initial, loading, goodsCount } = this.data;
        if(!logged && initial) {
            //如果没有登录判断是否刷新登录态
            this.logged();
        }

        //如果登录判断是否更新数据
        if(logged && loading){
            storage.get('cartCount').then((res) => {
                if(goodsCount !== res){
                    wx.startPullDownRefresh();
                }
            })
        }
    },

    /**
     * 管理商品
     */
    cartOperatTap() {
        this.toggle('operat');
    },

    /**
     * 优惠券
     */
    toggleCoupon() {
        this.toggle('showCoupon');
    },

    /**
     * 获取优惠券--网络请求
     */
    getCouponInfo(data, cb, a = true) {
        http.post(api.default, {
            data: {
                action: 'getcouponsfromshop',
                userid: this.data.userId,
                shopid: data,
            }
        }, a).then((res) => {
            this.setData({
                couponInfo: res.data.data,
            });

            cb && cb();
        });
    },

    /**
     * 获取优惠券
     */
    getCouponTap(e) {
        const data = e.currentTarget.dataset || e.target.dataset;

        if(data.id){
            this.getCouponInfo(data.id, () => {
                this.toggle('showCoupon');
            });
        }
    },

    /**
     * 点击领取优惠券
     */
    couponTap(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        http.post(api.default, {
            data: {
                action: 'getshopcoupon',
                userid: this.data.userId,
                CouponId: data.id,
            }
        }).then(() => {
            //重新获取优惠券
            this.getCouponInfo(data.shopId, () => {
                $toast(`优惠券领取成功`);
            }, false);
        })
    },

    /**
     * 跳转登录页
     */
    goLogin() {
        wxApi.setStartPage();
        wxApi.navigateTo(getPage.login);
    },

    /**
     * 获取购物车商品
     */
    getCartInfo(cb, a = false) {
        const { userId, userRank } = this.data;

        http.get(api.default, {
            data: {
                action: 'getcartlist',
                userid: userId,
                user_rank: userRank,
            }
        }, a).then((res) => {
            const cartData = res.data.data;
            cartData.shops.forEach((parentItem) => {
                parentItem.checkbox = false;
                parentItem.ProductList.forEach((item) => {
                    item.checkbox = false;
                })
            });

            this.setData({
                cartInfo: cartData,
                goodsCount: cartData.count
            });
            //更新购物车
            app.setCart(cartData.count);
            cb && cb();
        })
    },

    /**
     * 登录判断
     */
    logged(cb, nb) {
        //判断是否登录
        app.getLogin().then((res) => {
            this.setData({
                logged: res.code,
                userId: res.data.user.user_id,
                userRank: res.data.user.user_rank,
            });
            //获取购物车商品
            this.getCartInfo(() => {
                nb && nb();

                const { sumRecommend, pageIndex, userId } = this.data;

                http.post(api.default, {
                    data: {
                        action: 'GetCartRecommendProducts',
                        userid: userId,
                    }
                }, false).then((res) => {
                    const { data } = res.data;
                    let size = 20;

                    for(let i = 0; i < Math.ceil(data.list.length / size); i++){
                        let star = i * size;
                        let end = star + size;
                        sumRecommend.push(data.list.slice(star, end));
                    }

                    this.setData({ 
                        sumRecommend, 
                        recommendInfo: sumRecommend[pageIndex],
                        loadmore: false,
                    });
                });
            });
        }).catch((res) => {
            this.setData({
                logged: res
            });
        }).finally(() => {
            cb && cb();
        });
    },

    /**
     * 购物车数据集合处理
     */
    cartSort() {
        const goodsArr = [];
        const cartIdList =[];
        const allCountArr = [];
        const cartInfo = this.data.cartInfo;
        let allCheckbox = this.data.allCheckbox;
        let count = 0;
        let checkedCount = 0;
        let sumCount = 0;
        let sumAmount = 0;
        let allCount = 0;

        cartInfo.shops.forEach((parentItem, parentIndex) => {
            parentItem.ProductList.forEach((item) => {
                if(item.checkbox){
                    goodsArr.push(item);
                    checkedCount++
                }
                allCountArr.push(item.product_count);
                count++;
            })
        })

        //是否全选
        count === checkedCount ? allCheckbox = true : allCheckbox = false;
        
        goodsArr.forEach((item) => {
            //合计金额
            sumAmount += countMode.mul(item.order_price, item.product_count);
            //合计数量
            sumCount = countMode.add(sumCount, item.product_count);
            //cart id集合
            cartIdList.push(item.rec_id);
        });

        //合计数量
        allCountArr.forEach((item) => {
            allCount = countMode.add(allCount, item);
        })

        this.setData({
            allCheckbox: allCheckbox,
            sumCount: sumCount,
            sumAmount: sumAmount,
            cartIdList: cartIdList,
            goodsCount: allCount,
        });
        //更新购物车
        app.setCart(allCount);
    },

    /**
     * 全选店铺
     */
    shopCheckbox(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        const cartInfo = this.data.cartInfo;

        cartInfo.shops.forEach((parentItem, parentIndex) => {
            if (parentIndex === data.id){
                if (parentItem.checkbox){

                    parentItem.checkbox = false
                    parentItem.ProductList.forEach((item) => {
                        item.checkbox = false;
                    })
                }else{

                    parentItem.checkbox = true;
                    parentItem.ProductList.forEach((item) => {
                        item.checkbox = true;
                    })
                }
            }
        });

        this.setData({ cartInfo: cartInfo });
        this.cartSort();
    },

    /**
     * 选择商品
     */
    goodsCheckbox(e) {
        const data = e.currentTarget.dataset || e.target.dataset;
        const cartInfo = this.data.cartInfo;
        let checkedCount = 0;

        cartInfo.shops.forEach((parentItem, parentIndex) => {
            if (parentIndex === data.parentId){
                const _length = parentItem.ProductList.length;
                parentItem.ProductList.forEach((item, index) => {
                    if (index === data.id){
                        if(item.checkbox){
                            item.checkbox = false;
                            checkedCount--;
                        }else{
                            item.checkbox = true;
                            checkedCount++;
                        }
                    }else{
                        //是否全部选中
                        if(item.checkbox){
                            checkedCount++;
                        }
                    }
                });
                checkedCount === _length ? parentItem.checkbox = true : parentItem.checkbox = false;
            }
        });

        this.setData({ cartInfo: cartInfo });
        this.cartSort();
    },

    /**
     * 所有全选
     */
    allCheckbox() {
        const cartInfo = this.data.cartInfo;
        let allCheckbox = this.data.allCheckbox;

        if (allCheckbox){
            cartInfo.shops.forEach((parentItem) => {
                parentItem.checkbox = false;
                parentItem.ProductList.forEach((item) => {
                    item.checkbox = false;
                })
            });
        }else{
            cartInfo.shops.forEach((parentItem) => {
                parentItem.checkbox = true;
                parentItem.ProductList.forEach((item) => {
                    item.checkbox = true;
                })
            });
        }

        this.setData({ cartInfo: cartInfo });
        this.cartSort();
    },

    /**
     * 更新数量
     */
    stepperChange(e) {
        const count = e.detail;
        const data = e.currentTarget.dataset || e.target.dataset;
        const cartInfo = this.data.cartInfo;
        
        if (count){
            http.post(api.default, {
                data: {
                    action: 'update_cart',
                    pcount: count,
                    recid: data.id,
                    userid: this.data.userId,
                }
            }).then((res) => {
                //更新购物车数据
                cartInfo.shops[data.parentIndex].ProductList[data.index].product_count = count;
                //更新全局cart数据
                this.setData({
                    cartInfo: cartInfo
                })
                //更新购物车变化
                this.cartSort();
            })
        }
    },

    /**
     * 删除购物车选择商品
     */
    deleteClick() {
        const that = this;
        const goodsArr = this.data.cartIdList;
        if(goodsArr.length){
            wx.showModal({
                cancelText: '我再想想',
                cancelColor: '#576B95',
                confirmText: '删除',
                confirmColor: '#555555',
                content: `确定将这${goodsArr.length}个宝贝删除？`,
                success(res) {
                    if (res.confirm){
                        //确定删除
                        http.post(api.default, {
                            data: {
                                action: 'cartdelete',
                                recid: goodsArr,
                            }
                        }).then((res) => {
                            that.getCartInfo(() => {
                                $toast(`删除成功`,{
                                    icon: 'success'
                                });
                            },false);
                        })
                    }
                }
            });
        }else{
            $toast(`您还没有选择商品哦`);
        }
    },

    /**
     * 结算中心
     */
    checkoutClick() {
        const goodsArr = this.data.cartIdList;

        if (goodsArr.length){
            wxApi.navigateTo(getPage.order,{
                cartId: goodsArr.join('_'),
                source: 0,
            });
            //跳转结算，刷新当前
            this.onLoad();
        }else{
            $toast(`您还没有选择商品哦`);
        }
    },

    /**
     * 页面滚动条
     */
    onPageScroll(e) {
        if (e.scrollTop > 5){
            if (!this.data.topbarState){
                this.setData({ topbarState: true });
            }
        } else {
            if (this.data.topbarState){
                this.setData({ topbarState: false });
            }
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //登录
        this.logged(() => {
            this.setData({ initial: 1 });
        },() => {
            this.setData({ loading: 1 });
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        const { logged } = this.data;
        if(logged){
            //导航条加载
            wx.showNavigationBarLoading();
            //抖动
            wx.vibrateShort();
            //更新数据
            this.getCartInfo(() => {
                //成功后延迟0.5秒关闭动画
                setTimeout(() => {
                    wx.hideNavigationBarLoading();
                    wx.stopPullDownRefresh();
                },500);
                //取消全部选择
                this.setData({
                    allCheckbox: false,
                    sumAmount: 0,
                    sumCount: 0,
                });
            },false);
        }else{
            wx.stopPullDownRefresh();
        }
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        let { logged, pageIndex, loadmore, loaddone } = this.data;
        if (logged && !loaddone && !loadmore){
            pageIndex++;
            loadmore  = true;

            this.setData({ pageIndex, loadmore });

            //延迟1秒返回结果
            setTimeout(() => {
                let { sumRecommend, recommendInfo } = this.data;
                //判断是否加载完
                if (pageIndex == sumRecommend.length -1) loaddone = true;
                this.setData({
                    recommendInfo: recommendInfo.concat(sumRecommend[pageIndex]),
                    loadmore: false,
                    loaddone,
                });
            }, 1000);
        }
    },
})